package com.zhoun.service.impl;

import com.zhoun.common.ServerResponse;
import com.zhoun.dao.CategoryMapper;
import com.zhoun.pojo.Category;
import com.zhoun.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 获取全部分类列表
     * @return
     */
    public ServerResponse getCategoryList(){
        List<Category> categoryList = categoryMapper.getCategoryList();
        if (categoryList == null){
            return ServerResponse.createByErrorMessage("暂无数据");
        }
        return ServerResponse.createBySuccess(categoryList);
    }

    /**
     * 新增分类
     * @param category
     * @return
     */
    public ServerResponse addOrUpdate(Category category){
        if (category.getCategoryId() == null){
            if (categoryMapper.selectByCategoryName(category.getCategoryName()) != null){
                return ServerResponse.createByErrorMessage("分类已存在，请重新输入");
            }
            category.setStatus(0);
            int resultCount = categoryMapper.insert(category);
            if (resultCount == 0){
                return ServerResponse.createByErrorMessage("新增分类失败");
            }
            return ServerResponse.createBySuccess("新增分类成功",category);
        } else {
            if (categoryMapper.selectByCategoryName(category.getCategoryName()) != null){
                return ServerResponse.createByErrorMessage("分类已存在，请重新输入");
            }
            int resultCount = categoryMapper.updateByPrimaryKeySelective(category);
            if (resultCount == 0){
                return ServerResponse.createByErrorMessage("更新分类信息失败");
            }
            Category categoryNew = categoryMapper.selectByPrimaryKey(category.getCategoryId());
            return ServerResponse.createBySuccess("更新分类信息成功",categoryNew);
        }

    }

    /**
     * 删除分类
     * @param categoryId
     * @return
     */
    public ServerResponse delete(Integer categoryId){
        int resultCount = categoryMapper.deleteByPrimaryKey(categoryId);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("删除分类失败");
        }
        return ServerResponse.createBySuccessMessage("删除分类成功");
    }

    /**
     * 通过id查询分类
      * @param categoryId
     * @return
     */
    public ServerResponse getCategoryById(Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category == null){
            return ServerResponse.createByErrorMessage("未查询到数据");
        }
        return ServerResponse.createBySuccess(category);
    }



}
